package com.bdqn.t382.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.List;

@Component
public class RedisUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static Jedis redisConnection() {
        Jedis jedis = new Jedis("localhost", 6379);
        return jedis;
    }

    /**
     * 设置普通字符串键值对
     * @param key 键
     * @param value 值
     * @return 设置结果
     */
    public String setKey(String key, String value) {
        try (Jedis jedis = redisConnection()) {
            return jedis.set(key, value);
        }
    }

    /**
     * 设置带过期时间的键值对，支持存储列表数据
     * @param key 键
     * @param value 值，可以是列表或其他对象，会被序列化为 JSON 字符串存储
     * @param expire 过期时间（秒）
     * @return 设置结果
     */
    public String setKey(String key, Object value, int expire) {
        try (Jedis jedis = redisConnection()) {
            String jsonValue;
            if (value instanceof String) {
                jsonValue = (String) value;
            } else {
                try {
                    jsonValue = objectMapper.writeValueAsString(value);
                } catch (JsonProcessingException e) {
                    System.err.println("Error serializing value to JSON: " + e.getMessage());
                    return null;
                }
            }
            return jedis.setex(key, expire, jsonValue);
        }
    }

    public String getKey(String key) {
        return RedisUtil.redisConnection().get(key);
    }

    public <T> List<T> getListKey(String key, Class<T> elementType) {
        try (Jedis jedis = redisConnection()) {
            String json = jedis.get(key);
            if (json != null) {
                return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, elementType));
            }
            return null;
        } catch (JsonProcessingException e) {
            System.err.println("Error deserializing JSON to list: " + e.getMessage());
            return null;
        }
    }
}